from PyQt5.QtWidgets import QWidget, QCompleter, QTableWidgetItem
from PyQt5.QtCore import QDateTime, QDate, QTime,Qt
from qfluentwidgets import InfoBarPosition, InfoBar
from src.db_utils import *
from datetime import datetime
from ui.add_user_ui import Ui_adduser

class add_user_cls(Ui_adduser,QWidget):

    def __init__(self, parent=None):
        super().__init__(parent=parent)
        # self = Ui_adduser()
        self.setupUi(self)
        self.user_data = []
        self.updated_data = {}
        self.get_integrator()
        self.init_property()
        self.add_info.clicked.connect(self.add_user_info)
        self.update_info.clicked.connect(self.update_user_info)
        self.show_info.clicked.connect(self.show_user_info)
        self.update_table_info.clicked.connect(self.update_table_user_info)
    
    def init_property(self):
        ticket_query ='SELECT final_property FROM property'
        db = Database()
        db.fetch_data_and_update_combobox(ticket_query, self.custom_default_industry)

    def get_integrator(self):
        db = Database()
        integrator_tup = db.get_integrator()
        self.user_data = integrator_tup
        self.update_completers()

    def update_completers(self):
        usr_combined = [f"{item[1]}-{item[2]}-{item[3]}-{item[4]}-{item[5]}-{item[6]}-{item[7]}-{item[8]}-{item[9]}" for item in self.user_data]
        self.set_completer(self.custom_name, usr_combined,self.user_data, '姓名')
        usr_phones = [str(item[2]) for item in self.user_data]
        self.set_completer(self.custom_phone, usr_phones, self.user_data, '电话')
        usr_serial = [str(item[3]) for item in self.user_data]
        self.set_completer(self.serial_num, usr_serial, self.user_data, '序列号')

    def set_completer(self, widget, data, original_data, placeholder_text):
        completer = QCompleter(data, widget)
        completer.setCaseSensitivity(Qt.CaseInsensitive)
        completer.setMaxVisibleItems(10)
        widget.setCompleter(completer)
        widget.setClearButtonEnabled(True)
        widget.setPlaceholderText(placeholder_text)
        completer.activated.connect(lambda text: self.on_completer_activated(text, original_data, widget))

    def on_completer_activated(self, text, original_data, widget):
        for item in original_data:
            if text == f"{item[1]}-{item[2]}-{item[3]}-{item[4]}-{item[5]}-{item[6]}-{item[7]}-{item[8]}-{item[9]}":
                widget.setText(item[1])
                self.selected_usr_id = item[0]
                self.selected_usr_phone = str(item[2])
                self.custom_phone.setText(self.selected_usr_phone)
                self.selected_usr_serial = str(item[3])
                self.serial_num.setText(self.selected_usr_serial)
                self.selected_usr_company = item[4]
                self.custom_company.setText(self.selected_usr_company)
                self.selected_usr_department = item[5]
                self.custom_department.setText(self.selected_usr_department)
                self.selected_usr_area = item[6]
                self.custom_default_area.setText(self.selected_usr_area)
                self.selected_usr_saller = item[7]
                self.custom_default_saller.setText(self.selected_usr_saller)
                self.selected_serial_time = item[8]
                if self.selected_serial_time is not None:
                    time = datetime.strptime(self.selected_serial_time, "%Y-%m-%d")
                    formatted_date_str = time.strftime("%Y/%m/%d")
                    formatted_date_obj = datetime.strptime(formatted_date_str, "%Y/%m/%d")
                    self.custom_default_time.setDateTime(formatted_date_obj)
                else:
                    # 处理 self.selected_serial_time 为 None 的情况
                    # 例如，可以设置一个默认值或者记录一个错误日志
                    print("Error: self.selected_serial_time is None")
                self.selected_usr_industry = item[9]
                self.custom_default_industry.setText(self.selected_usr_industry)

    def get_user_data(self):
        custom_name = self.custom_name.text()
        custom_phone = self.custom_phone.text()
        serial_num = self.serial_num.text()
        custom_company = self.custom_company.text()
        custom_department = self.custom_department.text()
        custom_default_area = self.custom_default_area.text()
        default_saller = self.custom_default_saller.text()
        default_time = self.custom_default_time.dateTime().toPyDateTime().date()
        default_industry = self.custom_default_industry.text()
        
        if not custom_name or not custom_phone:
            InfoBar.warning(title='警告',content="请输入集成商姓名、电话！",orient=Qt.Horizontal,isClosable=True,position=InfoBarPosition.TOP_RIGHT,duration=2000,parent=self)
            return None
        return (custom_name, custom_phone, serial_num, custom_company,custom_department, custom_default_area,default_saller,default_time,default_industry)

    def data_clear(self):
        self.custom_name.clear()
        self.custom_phone.clear()
        self.serial_num.clear()
        self.custom_company.clear()
        # self.custom_default_area.clear()
        
    def add_user_info(self):
        user_data = self.get_user_data()
        if user_data is not None:
            try:
                db = Database()
                c = db.get_connection()
                c.execute('''CREATE TABLE IF NOT EXISTS integrator
                            (id INTEGER PRIMARY KEY AUTOINCREMENT, custom_name INTEGER, 
                            custom_phone INTEGER, serial_num INTEGER, custom_company TEXT, custom_department TEXT, custom_default_area TEXT, default_saller INTEGER, serial_pass_time DATE, industry INTEGER)''')
                
                c.execute("INSERT INTO integrator (custom_name, custom_phone, serial_num, custom_company, custom_department, custom_default_area, default_saller, serial_pass_time, industry ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", user_data)
                self.get_integrator()
                db.close_connection()
                event_emitter.notify(UserAddedEvent(new_user_data=user_data))
                InfoBar.success(title='用户添加',content="成功",orient=Qt.Horizontal,isClosable=True,position=InfoBarPosition.TOP_RIGHT,duration=2000,parent=self)
                self.data_clear()
            except sqlite3.Error as e:
                print("An error occurred:", e)
                InfoBar.error(title='用户添加',content="失败",orient=Qt.Horizontal,isClosable=True,position=InfoBarPosition.TOP_RIGHT,duration=2000,parent=self)

    def update_user_info(self):
        user_data = self.get_user_data()
        if user_data is not None:
            try:
                db = Database()
                c = db.get_connection()
                c.execute('''CREATE TABLE IF NOT EXISTS integrator
                            (id INTEGER PRIMARY KEY AUTOINCREMENT, custom_name INTEGER, 
                          custom_phone INTEGER, serial_num INTEGER, custom_company TEXT, custom_department TEXT, custom_default_area TEXT,default_saller INTEGER, serial_pass_time DATE, industry INTEGER)''')
                
                c.execute("UPDATE integrator SET custom_name = ?, custom_phone = ?, serial_num = ?, "
                          "custom_company = ?, custom_department  = ? , custom_default_area  = ? , default_saller = ?, serial_pass_time = ?, industry = ? WHERE id = ? ", 
                        (user_data[0], user_data[1], user_data[2], user_data[3], user_data[4], user_data[5], user_data[6], user_data[7],user_data[8],self.selected_usr_id))
                db.close_connection()
                self.get_integrator()
                event_emitter.notify(UserAddedEvent(new_user_data=user_data))
                InfoBar.success(title='成功',content="用户更新成功！",orient=Qt.Horizontal,isClosable=True,position=InfoBarPosition.TOP_RIGHT,duration=2000,parent=self)
                self.data_clear()
            except sqlite3.Error as e:
                print("An error occurred:", e)
                InfoBar.error(title='错误',content="无法更新用户！",orient=Qt.Horizontal,isClosable=True,position=InfoBarPosition.TOP_RIGHT,duration=2000,parent=self)

    def show_user_info(self):
        db = Database()
        c = db.get_connection()
        
        self.TableWidget.verticalHeader().hide()
        self.TableWidget.setHorizontalHeaderLabels(['姓名', '电话', '序列号', '默认公司', '默认部门', '默认区域', '默认销售', '过期时间','是否党政', 'id'])

        
        ticket_query = ("SELECT custom_name, custom_phone, serial_num, custom_company, "
                        "custom_department, custom_default_area,default_saller, serial_pass_time,industry, id FROM integrator")

        c.execute(ticket_query)
        ticket_sheet = c.fetchall()
        for i, integrator in enumerate(ticket_sheet):
            for j in range(0,10):
                value = integrator[j]
                str_tab = str(value) if value is not None else ''
                self.TableWidget.setItem(i, j, QTableWidgetItem(str_tab))
        self.TableWidget.resizeColumnsToContents()

    def update_table_user_info(self):
        db = Database()
        c = db.get_connection()
        updated_data = {}
        
        for row in range(self.TableWidget.rowCount()):
            item_id = self.TableWidget.item(row, 9)
            if item_id:
                record_id = item_id.text()
                if not record_id:
                    continue
                
                row_data = []
                # 这里是9，取0-8：姓名、电话、序列号、默认公司、默认部门、默认区域等9个字段
                for col in range(9):
                    item = self.TableWidget.item(row, col)
                    row_data.append(item.text() if item else '')
                
                updated_data[record_id] = row_data
        
        for record_id, row_data in updated_data.items():
            self.update_record_in_db(c, record_id, row_data)
        
        db.close_connection()
        self.updated_data.clear()
        self.show_user_info()
        InfoBar.info(title='信息',content="用户信息修改成功",orient=Qt.Horizontal,isClosable=True,position=InfoBarPosition.TOP_RIGHT,duration=20000,parent=self)
    def update_record_in_db(self, c, record_id, row_data):
        update_query = ("UPDATE integrator SET custom_name = ?, custom_phone = ?, serial_num = ?, custom_company = ?, "
                        "custom_department = ?, custom_default_area = ? , default_saller = ?, serial_pass_time = ?,industry WHERE id = ?")
        c.execute(update_query, (*row_data, record_id))